/*
 * @Descripttion: 封装socket方法
 * @version:
 */
import { ElMessage } from "element-plus";
interface socket {
  websocket: any;
  connectURL: string;
  socket_open: boolean;
  hearbeat_timer: any;
  hearbeat_interval: number;
  is_reonnect: boolean;
  reconnect_count: number;
  reconnect_current: number;
  recnnect_number: number;
  reconnect_timer: any;
  reconnect_interval: number;
  init: (receiveMessage: Function | null, url?: string) => any;
  msg: (receiveMessage: Function | null, url?: string) => any;
  receive: (message: any) => void;
  heartbeat: () => void;
  send: (data: any, callback?: any) => void;
  close: () => void;
  reconnect: () => void;
  receive_message: Function | null;
}

export interface MessageItem {
  type: string;
  user_type: string;
  group_id: string;
  user_id: string;
  content: string | any;
  uid: string;
}
/*
  ID           uint   `json:"id"`
	GroupID      uint   `json:"group_id"`
	UserID       uint   `json:"user_id"`
	UserType     string `json:"user_type"`
	Content      string `json:"content"`
	Type         string `json:"type"`
	Status       uint8  `json:"status"`
	CreatedAt    int64  `json:"created_at"`
	CreatedAtStr string `json:"created_at"`
*/
export interface ChatHistory {
  /** ID */
  id: number;
  /** 对话组ID */
  group_id: number;
  /** 用户ID */
  user_id: number;
  /** 用户昵称 */
  nick_name: string;
  /** 头像 */
  head_img: string;
  /** 用户类型 */
  user_type: string;
  /** 内容 */
  content: string;
  /** 类型 */
  type: string;
  /** 状态 */
  status: number;
  /** 创建时间 */
  created_at: number;
  /** 创建时间 */
  created_at_str: string;
}
/*
  ID        uint   `json:"id"`
	AdminID   uint   `json:"admin_id"`
	ManageID  uint   `json:"manage_id"`
	UserID    uint   `json:"user_id"`
	HeadImg   string `json:"head_img"`
	Username  string `json:"username"`
	UnRead    uint   `json:"un_read"`
	CreatedAt string `json:"updated_at"`
*/
export interface GroupItem {
  /** ID */
  id: number;
  /** 创建人ID */
  admin_id: number;
  /** 管理员ID */
  manage_id: number;
  /** 用户ID */
  user_id: number;
  /** 头像 */
  head_img: string;
  /** 用户名 */
  username: string;
  /** 手机号 */
  phone: string;
  /** 邮箱 */
  email: string;
  /** 未读消息数 */
  un_read: number;
  /** 是否在线 */
  online: number;
  /** 是否置顶 */
  is_top: number;
  /** 创建时间 */
  updated_at_str: string;
  /** 最后一条消息 */
  last_msg: ChatHistory;
}

const socket: socket = {
  websocket: null,
  connectURL: import.meta.env.VITE_APP_WS_URL, //userHook.getSocketUrl(),
  // 开启标识
  socket_open: false,
  // 心跳timer
  hearbeat_timer: null,
  // 心跳发送频率
  hearbeat_interval: 9000,
  // 是否自动重连
  is_reonnect: true,
  // 重连次数
  reconnect_count: 3,
  // 已发起重连次数
  reconnect_current: 1,
  // 网络错误提示此时
  recnnect_number: 0, // 修正：将 ronnect_number 改为 reconnect_number
  // 重连timer
  reconnect_timer: null,
  // 重连频率
  reconnect_interval: 5000,
  //  接收消息
  receive_message: null,

  msg: (receiveMessage: Function | null, url?: string) => {
    if (!("WebSocket" in window)) {
      ElMessage.warning("浏览器不支持WebSocket");
      return null;
    }
    if (receiveMessage == null) {
      return null;
    }
    socket.receive_message = receiveMessage;
    // console.log('进来执行了');
    socket.websocket = new WebSocket(url || "");
    socket.websocket.onmessage = (e: any) => {
      if (receiveMessage) {
        receiveMessage(e);
      }
    };

    socket.websocket.onclose = (e: any) => {
      clearInterval(socket.hearbeat_timer);
      socket.socket_open = false;
      console.log("链接关闭,尝试重联");
      // 需要重新连接
      if (socket.is_reonnect) {
        socket.reconnect_timer = setTimeout(() => {
          // 超过重连次数
          if (socket.reconnect_current > socket.reconnect_count) {
            clearTimeout(socket.reconnect_timer);
            socket.is_reonnect = false;
            return;
          }
          // 记录重连次数
          socket.reconnect_current++;
          socket.reconnect();
        }, socket.reconnect_interval);
      }
    };

    // 连接成功
    socket.websocket.onopen = function (e: any) {
      socket.socket_open = true;
      socket.is_reonnect = true;
      socket.reconnect_current = 1;
      console.log("消息连接成功");
      socket.send({
        type: "login",
        content: localStorage.getItem("accessToken"),
      });
      // 开启心跳
      socket.heartbeat();
      // console.log(e);
      // console.log('链接成功');
    };

    // 连接发生错误
    socket.websocket.onerror = function () {
      console.log("链接失败");
    };
  },

  init: (receiveMessage: Function | null, url?: string) => {
    socket.msg(receiveMessage, url);
  },
  send: (data, callback = null) => {
    // 开启状态直接发送
    if (socket.websocket.readyState === socket.websocket.OPEN) {
      data.user_type = "admin";
      socket.websocket.send(JSON.stringify(data));
      if (callback) {
        callback();
      }
      // 正在开启状态，则等待1s后重新调用
    } else {
      clearInterval(socket.hearbeat_timer);
      if (socket.recnnect_number < 1) {
        // 修正：将 ronnect_number 改为 reconnect_number
        ElMessage({
          type: "error",
          message: "chat.unopen",
          duration: 6000,
        });
      }
      socket.recnnect_number++; // 修正：将 ronnect_number 改为 reconnect_number
    }
  },

  receive: (message: any) => {
    let params = [];
    params = JSON.parse(message);
    return params;
  },

  heartbeat: () => {
    if (socket.hearbeat_timer) {
      clearInterval(socket.hearbeat_timer);
    }

    socket.hearbeat_timer = setInterval(() => {
      const data = {
        type: "ping",
        content: "ping",
      };
      socket.send(data);
    }, socket.hearbeat_interval);
  },

  close: () => {
    const data = {
      type: "logout",
      content: localStorage.getItem("accessToken"),
    };
    socket.send(data);
    clearInterval(socket.hearbeat_interval);
    socket.is_reonnect = false;
    socket.websocket.close();
  },

  /**
   * 重新连接
   */
  reconnect: () => {
    if (socket.websocket && !socket.is_reonnect) {
      socket.close();
    }
    console.log("重新链接");
    const url: string = import.meta.env.VITE_APP_WS_URL ?? ""; // 修正：使用正确的 store 方法获取 URL
    if (url !== "") {
      console.log("重新链接" + url);
      socket.msg(socket.receive_message, url);
    }
  },
};

export default socket;
